package com.nyist.myticket.core.redis;

import com.nyist.myticket.core.base.ApplicationContextFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;

/**
 * @author yangxiaogen
 * @date 2021/6/15 17:15
 */
//@Deprecated
public class RedisFactory {

    public static Jedis getJedis() {
        JedisPool jedisPool = (JedisPool) ApplicationContextFactory.getBean("jedisPool");
        //JedisPool jedisPool = (JedisPool) ApplicationContextFactory.getBean(RedisConfiguration.class);
        return jedisPool.getResource();
    }

    /**
     * 保存数据，不修改失效时间
     * @param key
     * @param value
     */
    public static void setValue(String key, String value) {
        Jedis redis = null;
        try {
            redis = getJedis();
            Long ttl = redis.ttl(key);
            redis.set(key, value);
            redis.expire(key, ttl.intValue());
        } finally {
            if (redis != null) {
                redis.close();
            }
        }

    }

    /**
     * 保存数据，没有失效时间
     * @param key
     * @param value
     */
    public static void setValueWithoutExpire(String key, String value) {
        Jedis redis = null;
        try {
            redis = getJedis();
            redis.set(key, value);
        } finally {
            if (redis != null) {
                redis.close();
            }
        }

    }

    /**
     * 获取 缓存中的值
     *
     * @returne
     */
    public static String getValue(String key) {
        Jedis redis = null;
        try {
            redis = getJedis();
            return redis.get(key);
        } finally {
            if (redis != null) {
                redis.close();
            }
        }
    }

    /**
     * 保存数据
     *
     * @param key
     */
    public static void setValue(String key, String value, int expireTime) {
        Jedis redis = null;
        try {
            redis = getJedis();
            redis.set(key, value);
            redis.expire(key, expireTime);
        } finally {
            if (redis != null) {
                redis.close();
            }
        }

    }

    /**
     * 删除数据
     *
     * @param pattern
     */
    public static void removeData(String pattern) {
        Jedis redis = null;
        try {
            redis = getJedis();
            Set<String> keys = redis.keys("*" + pattern);
            if (keys == null || keys.size() == 0) {
                return;
            }
            for (String key : keys) {
                redis.del(key);
            }
        } finally {
            if (redis != null) {
                redis.close();
            }
        }
    }
}
